package com.yuesystem.controller;

import com.yuesystem.common.BaseContext;
import com.yuesystem.common.CustomException;
import com.yuesystem.common.R;
import com.yuesystem.entity.OfficeItem;
import com.yuesystem.service.ChangeItem2Service;
import com.yuesystem.service.OfficeItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 官职修改条目类.
 */
@RestController
@CrossOrigin
@RequestMapping("/changes2")
@Slf4j
public class ChangeItem2Controller {
  @Autowired
  private ChangeItem2Service changeItemService;

  @Autowired
  private OfficeItemService officeItemService;

  /**
   * 新增编辑条目.
   *
   * @param officeItem 官职条目类
   * @return 新增成功与否的提示信息
   */
  @PostMapping
  public R<String> add(@RequestBody OfficeItem officeItem) {
    int status = BaseContext.getCurrentUser().getStatus();
    if (status == 0) {
      throw new CustomException("您未获得该权限！");
    }
    changeItemService.addItem(officeItem);
    return R.success("添加条目成功！");
  }

  /**
   * 通过某个官职条目ID删除某个条目.
   *
   * @param itemId 官职条目id
   * @return 删除成功与否的提示信息
   */
  @DeleteMapping("/{itemId}")
  public R<String> delete(@PathVariable Long itemId) {
    int status = BaseContext.getCurrentUser().getStatus();
    if (status == 0) {
      throw new CustomException("您未获得该权限！");
    }
    // 根据书院获得具体的书院条目信息
    OfficeItem officeItem = officeItemService.getById(itemId);
    if (officeItem == null || officeItem.getIsDeleted() == 1) {
      return R.error("该条目不存在，请刷新后重试！");
    }
    changeItemService.deleteItem(officeItem);
    return R.success("删除条目成功！");
  }

  /**
   * 修改官职条目信息.
   *
   * @param officeItem 官职条目类
   * @return 修改成功与否的提示信息
   */
  @PutMapping
  public R<String> update(@RequestBody OfficeItem officeItem) {
    int status = BaseContext.getCurrentUser().getStatus();
    if (status == 0) {
      throw new CustomException("您未获得该权限！");
    }
    changeItemService.updateItem(officeItem);
    return R.success("修改条目成功！");
  }
  

}
